#pragma once
#include <iostream>
namespace bit
{
	template<class T>
	class vector {
	public:
		typedef T* iterator;
		typedef const T* const_iterator;
		vector()
		{}
		vector(const vector<T>& v)
		{
			reserve(v.capacity());
			for (auto& e : v) {
				push_back(e);
			}
		}
		~vector() {
			delete[]_start;
			_start = _finish = _endOfStorage = nullptr;
		}
		iterator begin() {
			return _start;
		}
		iterator end() {
			return _finish;
		}
		const_iterator begin() const{
			return _start;
		}
		const_iterator end() const{
			return _finish;
		}
		iterator operator[] (size_t pos) {
			assert(pos < size());
			return _start[pos];
		}
		const_iterator operator[] (size_t pos) const{
			assert(pos < size());
			return _start[pos];
		}
		size_t size() const{
			return _finish - _start;
		}
		size_t capacity() const{
			return _endOfStorage - _start;
		}
		void reserve(size_t n) {
			if (n > capacity())
			{
				iterator tmp = new T[n];
				size_t old_size = size();
				memcpy(tmp, _start, size() * sizeof(T));
				delete[]_start;
				_start = tmp;
				_finish = _start + old_size;
				_endOfStorage = _start + n;
			}
		}
		void resize(size_t n, const T& val = T()) {
			if (n > capacity())
			{
				reserve();
				while (_finish < _endOfStorage)
				{
					*_finish = val;
					_finish++;
				}
			}
			else {
				_finish = _start + n;
			}
		}
		void insert(iterator pos , const T& val) {
			assert(pos >= _start);
			assert(pos <= _finish);
			if (_finish == _endOfStorage)
			{
				size_t len = pos - _start;
				reserve(capacity() == 0 ? 4 : capacity() * 2);
				pos = _start + len;
			}
			iterator it = end() - 1;
			while (it >= pos)
			{
				*(it + 1) = *it;
				it--;
			}
			*pos = val;
			_finish++;
		}
		void erase(iterator pos) {
			assert(!empty());
			assert(pos >= _start);
			assert(pos < _finish);
			iterator it = pos + 1;
			while (it < _finish)
			{
				*(it - 1) = *it;
				++it;
			}
			--_finish;
		}
		void push_back(const T& val) {
			if (_finish == _endOfStorage)
			{
				reserve(capacity() == 0 ? 4 : capacity() * 2);
			}
			*_finish = val;
			++_finish;
		}
		void pop_back() {
			assert(!empty());
			--_finish;
		}
		void empty() {
			return _start == _finish;
		}
	private:
		iterator _start = nullptr;
		iterator _finish = nullptr;
		iterator _endOfStorage = nullptr;
	};
}
